package com.sihai.core.beans;

import org.apache.commons.lang.StringUtils;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;

public class BeanInjectionAnnotationResolver {

    /**
     * 根据Field上的@Bean annotation定义寻找合适的Bean引用
     *
     * @param field field which defind @Bean
     * @return bean reference or throw exception if not found
     */
    public static Object resolve(Field field) {
        Object bean = null;
        Annotation[] annotations = field.getDeclaredAnnotations();
        for (Annotation annotation : annotations) {
            if (annotation.annotationType() == BeanInject.class) {
                BeanInject beanReference = (BeanInject) annotation;
                if (StringUtils.isNotBlank(beanReference.value())) {//user define bean name manually
                    bean = BeanLocator.getBean(beanReference.value());
                } else {
                    bean = BeanLocator.getBean(field.getName());
                }
                break;
            }
        }
        return bean;
    }
}
